import { login, logout, getInfo } from '@/api/user'
import { isExternal } from '@/utils/validate'
import Astrict from '@/utils/astrict'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  Token: getToken(),
  name: '',
  avatar: '',
  UserID:'',
  UserRole:'',
  DateTime:'',
  introduction: '',
  DefaultPageLength:10,
  UIOperaTime:0,
  DefaultLogDays:0,
  SumDays:0,
  EventLevel:0,
  FirstCreate:'',
  roles: []
}
let rolesarr = [];
const mutations = {
  SET_TOKEN: (state, Token) => {
    state.Token = Token
  },
  SET_DATETIME: (state, DateTime) => {
    state.DateTime = DateTime;
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERROLE:(state,UserRole)=>{
    state.UserRole = UserRole
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_UIOPERATIME:(state,UIOperaTime) =>{
    state.UIOperaTime = UIOperaTime
  },
  SET_EVENTLEVEL: (state, EventLevel)=> {
    state.EventLevel = EventLevel
  },
  SET_USERID:(state,UserID)=>{
    state.UserID = UserID
  },
  SET_SUMDAY:(state,SumDays)=>{
    state.SumDays = SumDays
  },
  SET_PAGELENGTH:(state, DefaultPageLength) =>{
    state.DefaultPageLength = DefaultPageLength
  },
  SET_LOGDAYS:(state, DefaultLogDays) =>{
    state.DefaultLogDays = DefaultLogDays
  },
  SET_FIRSTCREATE: (state, FirstCreate) => {
    state.FirstCreate = FirstCreate
  },
  getroles: (state, rolosdata) => {
    rolesarr = [];
    function getmenurolos(rolosdata){
      rolesarr.push(rolosdata.RootRole);

    }
    getmenurolos(rolosdata,state);
  }
}

const actions = {
  // 登录
  login({ commit }, userInfo) {
    // const serverLoginUrl = '/login';
    const { UserID, Password } = userInfo.Data

    return new Promise((resolve, reject) => {
      login({
        Header:{
          "CmdCode":"Login"
        },
        Data:{
          UserID: UserID,
          Password: Password
        }
      }).then(response => {
        const  data  = response

          commit('SET_TOKEN', data.Token)
          commit('SET_FIRSTCREATE',data.Data.FirstCreate);
          setToken(data.Token)

        resolve()
      }).catch(error => {
          const data = error;
          console.log(data);
          if (data.Data) {
            if (data.Data.FirstCreate === 1) {
              commit('SET_USERROLE', data.Data.UserRole)
              commit('SET_FIRSTCREATE',data.Data.FirstCreate);
            }
            reject(error)
          }else{
            reject(error)
          }
          // }else if (data.Status.StatusCode === 32769) {
          //   console.log(data.Status.StatusCode);
          //   commit('SET_STATUS',data.Status.StatusCode)
          // }


        // return error
      })
    })
  },

  // get user info
  getInfo({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      getInfo({
        Header:{
          "CmdCode":"GetGlobalInfo",
          "PageName":""
        },
        Token:state.Token
      }).then(response => {
        commit('getroles', response.Data);

        // let obj = {};
        //         response.Data.map(item => {
        //           obj[item.Name] = item.Right;
        //         });
        // const Right = obj;
        let overTime = 0;
        const DateTime = response.Data.DateTime;
        // let value = '';
        // response.Data.Threshold.map(item=>{
        //   if (item.Name==='is_verify_password') {
        //     value = item.Value;
        //   }else if(item.Name === 'ui_opera_expire_time'){
        //     overTime = item.Value;
        //   }
        // });
        const Product = response.Data.Product
        const DefaultPageLength = response.Data.DefaultPageLength
        const UIOperaTime = response.Data.UIOperaTime
        const UserID = response.Data.UserID;
        const DefaultLogDays = response.Data.DefaultLogDays
        const SumDays = response.Data.SumDays
        const EventLevel = response.Data.EventLevel
        // const is_verify_password = value;
        let { data } = {data:{roles: rolesarr}}; //获取权限码
        // console.log(data);

        if (!data) {
          reject('当前用户登入信息已失效，请重新登入再操作.');
        }
        const { name, avatar, roles } = data
        if (!roles || roles.length <= 0) {
          reject('用户没有角色权限!');
        }

        // commit('SET_RIGHT', Right);
        commit('SET_USERID',UserID);
        commit('SET_ROLES', roles);
        commit('SET_SUMDAY',SumDays)
        commit('SET_PAGELENGTH', DefaultPageLength);
        commit('SET_UIOPERATIME', UIOperaTime);
        commit('SET_LOGDAYS', DefaultLogDays);
        commit('SET_EVENTLEVEL',EventLevel);
        // commit('SET_VALUE', is_verify_password);
        commit('SET_DATETIME', DateTime);
        // commit('SET_OVERTIME', overTime);
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        // commit('SET_PRODUCT', Product)
        resolve(data)
        Astrict(UIOperaTime);
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
      const serverLogoutUrl = '/cfunc';
      if (isExternal(serverLogoutUrl)) {
        return new Promise((resolve) => {
          commit('SET_TOKEN', '');
          commit('SET_ROLES', []);
          window.location.href = serverLogoutUrl;
          resolve({isExternal: true, siteLoginRouter: siteLoginRouter});
        });
      } else {
        return new Promise((resolve, reject) => {
          logout({
            Header:{
              "CmdCode":"Logout",
              "PageName":""
            },
            Token:state.Token
          }).then(() => {
           
            commit('SET_TOKEN', '')
            commit('SET_ROLES', []);
            removeToken()
            resetRouter()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      }
    },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const Token = role + '-Token'

    commit('SET_TOKEN', Token)
    setToken(Token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
